package com.digitalchina.lxnsy.activity.old;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessEvaluate;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.AssessOptsVO;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.viewholder.AssessOptsHolder;
import com.hedgehog.ratingbar.RatingBar;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/3/3 11:27
 * 修改备注：
 * ================================================
 */
public class IssueEvaluateActivity extends BaseActivity {

    @Bind(R.id.issue_evaluate_ratingbar)
    RatingBar issueEvaluateRatingbar;
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.issue_evaluate_et_opinion)
    EditText issueEvaluateEtOpinion;
    @Bind(R.id.issue_evaluate_btn_submit)
    Button issueEvaluateBtnSubmit;

    private RecyclerArrayAdapter adapter;
    private String starNum = "";
    private int maxCheckNum = 0; // 最多只能选择3个

    private String expertId = ""; // 专家ID
    private String firstAskTime = ""; // 首次提问时间
    private Map<String, Object> map = new HashMap<>();

    private String assessId = "";

    private List<AssessOptsVO> optsVOList = new ArrayList<>();

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_issue_evaluate);
        setTitle("服务评价");
    }

    @Override
    public void initMember() {
        map = (Map<String, Object>) getIntent().getSerializableExtra("map");
        expertId = map.containsKey("expertId") ? (String) map.get("expertId") : "";
        assessId = map.containsKey("assessId") ? (String) map.get("assessId") : "";
        firstAskTime = map.containsKey("sendTime") ? (String) map.get("sendTime") : DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD_EN_HH_MM_SS);

        initRecyclerView();

        BusinessEvaluate.getAssessOpts(this, mHandler);
    }

    private void initRecyclerView() {


        recyclerView.setLayoutManager(new LinearLayoutManager(this));


        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new AssessOptsHolder(parent);
            }
        });


    }

    /**
     * 选择条目拼接成array
     *
     * @return
     */
    private String[] getCheckArray() {


        List<AssessOptsVO> tempList = new ArrayList<>();
        for (int i = 0; i < optsVOList.size(); i++) {
            if (optsVOList.get(i).isChecked()) {
                tempList.add(optsVOList.get(i));
            }
        }

        String strArray[] = new String[tempList.size()];
        for (int i = 0; i < tempList.size(); i++) {
            strArray[i] = tempList.get(i).getCode();
        }

        return strArray;

    }

    @Override
    public void addListener() {

        /**
         * 打分监听
         */
        issueEvaluateRatingbar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() {
            @Override
            public void onRatingChange(float RatingCount) {
                starNum = String.valueOf((int) RatingCount);
            }
        });



        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        /**
         * 选项监听
         */
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                AssessOptsVO optsVO = (AssessOptsVO) adapter.getItem(position);
                if (optsVO.isChecked()) {
                    optsVO.setChecked(false);
                    maxCheckNum--;
                } else {
                    if (maxCheckNum == 3) {
                        showToast("最多只能选择3条");
                        return;
                    }
                    optsVO.setChecked(true);
                    maxCheckNum++;
                }

                adapter.notifyDataSetChanged();
            }
        });

        /**
         * 提交监听
         */
        issueEvaluateBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (StringUtil.isStrEmpty(starNum)) {
                    showToast("请给本次服务打分");
                    return;
                }

                BusinessEvaluate.saveServiceAssess(IssueEvaluateActivity.this, starNum, issueEvaluateEtOpinion.getText().toString(), getCheckArray(), assessId, mHandler);
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_GET_ASSESS_OPTS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_ASSESS_OPTS_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_SAVE_SERVICE_ASSESS_SUCCESS:
                        showToast("评价成功");
                        finish();
                        ActivityTaskManager.getInstance().closeActivity(HelpAndSupportActivity.class);
                        ActivityTaskManager.getInstance().closeActivity(ConsultIssueV2Activity.class);
                        ActivityTaskManager.getInstance().closeActivity(IssueDetailActivity.class);
                        ActivityTaskManager.getInstance().closeActivity(ConversationActivity.class);
                        break;
                    case MSG.MSG_SAVE_SERVICE_ASSESS_FIELD:
                        showToast(msg.obj.toString());
                        break;

                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        optsVOList = FastJsonUtil.getListBean(object.toString(), "body", "opts", AssessOptsVO.class);

        if (optsVOList != null && optsVOList.size() > 0)
            adapter.addAll(optsVOList);
        else
            recyclerView.showEmpty();
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
